package com.mrd.gtimp.business.action;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrd.constant.HgDataConstants;
import com.mrd.constant.MsgConstants;
import com.mrd.framework.config.web.json.Result;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.HgData;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.HgDataBiz;
import com.mrd.gtimpframe.service.HgDataService;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.LoginUtil;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Controller
@RequestMapping("/business")
public class BizInterfaceAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private HgDataBiz hgDataBiz;
    @Resource
    private DeclarationBiz declarationBiz;
    @Resource
    private JedisClientClusterImpl jedisClientCluster;
    @Resource
    private HgDataService hgDataService;

    private Declaration declaration;

    public Declaration getDeclaration() {
        return declaration;
    }

    public void setDeclaration(Declaration declaration) {
        this.declaration = declaration;
    }
    // -----2.0改进需求

    /**
     * 保存转关操作数据 跨域接口示例：http://192.168.0.214:8080/business/bi-doZhuanGuan?callback=callback&id=f8ccca0e58568ac50158569b8eb80000&data_type=直航or转关&ship_name=船名&voyage_no=航次号&bl_no=提运单号&transport_na=运输工具名称&export_port=出口口岸&ship_code=船舶代码
     */
    @RequestMapping("/bi-doZhuanGuan")
    @ResponseBody
    public Result doZhuanGuan(HttpServletRequest request, Declaration declaration) {
        Result jmsg;
        String msg = "";
        try {
            String id = request.getParameter("id");
            if (jedisClientCluster.get("lock_decla_" + id, String.class) != null) {
                return Result.newFailInstance("{\"msg\":\"报关单已被锁定，解锁前不能进行操作!\"}");
            }
            if (StringUtils.isEmpty(id) || declaration == null) {
                throw new Exception("参数不正确");
            } else {
                Declaration fd = declarationBiz.findEntityById(id);
                if (fd == null) {
                    throw new Exception(String.format("单证编号[%s]不存在。", id));
                } else if ("DS10".equals(fd.getState())) {// 当平台状态为“海关已放行”时，单证信息不允许再手工同步
                    throw new Exception(String.format("单证[%s]当前状态是“海关已放行”，不再允许同步数据。", fd.getBusinessId()));
                }
            }
            List<String> properties = new ArrayList<String>();
            if (StringUtils.isNotEmpty(declaration.getExport_port())) {
                Map<String, Object> parameters = new HashedMap() {
                    {
                        put("name", declaration.getExport_port());
                        put("type", HgDataConstants.HG_CUSTOMS_TYPE);
                    }
                };
                List<Object> r = hgDataBiz.findObjectByHql("from com.mrd.gtimp.business.entity.HgData d where d.name = :name and d.type=:type", 0, 1, parameters);
                if (r.size() > 0) {
                    properties.add("export_port");
                    properties.add("export_port_code");
                    declaration.setExport_port_code(((HgData) r.get(0)).getCode());
                } else {
                    throw new Exception(String.format("口岸信息:[%s]不存在.", declaration.getExport_port()));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getData_type())) {
                properties.add("data_type");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_name())) {
                properties.add("ship_name");
            }
            if (StringUtils.isNotEmpty(declaration.getVoyage_no())) {
                properties.add("voyage_no");
            }
            if (StringUtils.isNotEmpty(declaration.getBl_no())) {
                properties.add("bl_no");
            }
            if (StringUtils.isNotEmpty(declaration.getTransport_na())) {
                properties.add("transport_na");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_code())) {
                properties.add("ship_code");
            }
            //业务为转关时，清空客户录入的“提运单号”和“航次号”
            if ("转关".equals(declaration.getData_type())) {
                declaration.setVoyage_no("");
                declaration.setBl_no("");
                properties.add("voyage_no");
                properties.add("bl_no");
            }
            if (properties.size() > 0) {
                declaration.setId(id);
                declaration.setMtime(new Date());
                properties.add("MTIME");
                declarationBiz.updateEntity(declaration, properties);
                msg = MsgConstants.OPERATION_SUCCESS;
                jmsg = Result.newSuccessInstance(msg);
            } else {
                msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), "", "\"}");
                jmsg = Result.newFailInstance(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), e.getMessage(), "\"}");
            jmsg = Result.newFailInstance(msg);
        }
        return jmsg;
    }

    /**
     * 线下供应商转关 线下供应商转关，同时更改状态为复审
     *
     * @author han
     */
    @RequestMapping("/bi-offlineDoZhuanGuan")
    @ResponseBody
    public Result offlineDoZhuanGuan(HttpServletRequest request, Declaration declaration) throws Exception {
        Result jmsg;
        String msg = "";
        try {
            String id = request.getParameter("id");
            if (StringUtils.isEmpty(id) || declaration == null) {
                throw new Exception("参数不正确");
            } else {
                Declaration fd = declarationBiz.findEntityById(id);
                if (fd == null) {
                    throw new Exception(String.format("单证编号[%s]不存在。", id));
                } else if ("DS10".equals(fd.getState())) {// 当平台状态为“海关已放行”时，单证信息不允许再手工同步
                    throw new Exception(String.format("单证[%s]当前状态是“海关已放行”，不再允许同步数据。", fd.getBusinessId()));
                }
            }
            List<String> properties = new ArrayList<String>();
            if (StringUtils.isNotEmpty(declaration.getExport_port())) {
                Map<String, Object> parameters = new HashedMap() {
                    {
                        put("name", declaration.getExport_port());
                        put("type", HgDataConstants.HG_CUSTOMS_TYPE);
                    }
                };
                List<Object> r = hgDataBiz.findObjectByHql("from com.mrd.gtimp.business.entity.HgData d where d.name = :name and d.type=:type", 0, 1, parameters);
                if (r.size() > 0) {
                    properties.add("export_port");
                    properties.add("export_port_code");
                    declaration.setExport_port_code(((HgData) r.get(0)).getCode());
                } else {
                    throw new Exception(String.format("口岸信息:[%s]不存在.", declaration.getExport_port()));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getData_type())) {
                properties.add("data_type");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_name())) {
                properties.add("ship_name");
            }
            if (StringUtils.isNotEmpty(declaration.getVoyage_no())) {
                properties.add("voyage_no");
            }
            if (StringUtils.isNotEmpty(declaration.getBl_no())) {
                properties.add("bl_no");
            }
            if (StringUtils.isNotEmpty(declaration.getTransport_na())) {
                properties.add("transport_na");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_code())) {
                properties.add("ship_code");
            }
            if (properties.size() > 0) {
                declaration.setId(id);
                declaration.setMtime(new Date());
                declaration.setState(Declaration.DeclarationBusinessState.SEC_PAS);
                declaration.setValidateTime(new Date());
                declaration.setValidator(LoginUtil.getLoginUser());
                properties.add("MTIME");
                properties.add("validateTime");
                properties.add("validator");
                properties.add("state");
                declarationBiz.updateEntity(declaration, properties);
                msg = MsgConstants.OPERATION_SUCCESS;
                jmsg = Result.newSuccessInstance(msg);
            } else {
                msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), "", "\"}");
                jmsg = Result.newFailInstance(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), e.getMessage(), "\"}");
            jmsg = Result.newFailInstance(msg);
        }
        return jmsg;
    }

    @RequestMapping("/bi-doZhuanGuan-jsoup")
    @ResponseBody
    public void doZhuanGuan(HttpServletRequest request, Declaration declaration, HttpServletResponse response) {
        Result jmsg;
        String msg = "";
        try {
            String id = request.getParameter("id");
            if (jedisClientCluster.get("lock_decla_" + id, String.class) != null) {
                response.setHeader("X-Content-Type-Options", "application/javascript");
                String data = new ObjectMapper().writeValueAsString(Result.newFailInstance("报关单已被锁定，解锁前不能进行操作"));
                PrintWriter pw = response.getWriter();
                pw.write(String.format("%s(%s)", request.getParameter("callback"), data));
                pw.flush();
                return;
            }
            if (StringUtils.isEmpty(id) || declaration == null) {
                throw new Exception("参数不正确");
            } else {
                Declaration fd = declarationBiz.findEntityById(id);
                if (fd == null) {
                    throw new Exception(String.format("单证编号[%s]不存在。", id));
                } else if ("DS10".equals(fd.getState())) {// 当平台状态为“海关已放行”时，单证信息不允许再手工同步
                    throw new Exception(String.format("单证[%s]当前状态是“海关已放行”，不再允许同步数据。", fd.getBusinessId()));
                }
            }
            List<String> properties = new ArrayList<String>();
            if (StringUtils.isNotEmpty(declaration.getExport_port())) {
                Map<String, Object> parameters = new HashedMap() {
                    {
                        put("name", declaration.getExport_port());
                        put("type", HgDataConstants.HG_CUSTOMS_TYPE);
                    }
                };
                List<Object> r = hgDataBiz.findObjectByHql("from com.mrd.gtimp.business.entity.HgData d where d.name = :name and d.type=:type", 0, 1, parameters);
                if (r.size() > 0) {
                    properties.add("export_port");
                    properties.add("export_port_code");
                    declaration.setExport_port_code(((HgData) r.get(0)).getCode());
                } else {
                    throw new Exception(String.format("口岸信息:[%s]不存在.", declaration.getExport_port()));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getData_type())) {
                properties.add("data_type");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_name())) {
                properties.add("ship_name");
            }
            if (StringUtils.isNotEmpty(declaration.getVoyage_no())) {
                properties.add("voyage_no");
            }
            if (StringUtils.isNotEmpty(declaration.getBl_no())) {
                properties.add("bl_no");
            }
            if (StringUtils.isNotEmpty(declaration.getTransport_na())) {
                properties.add("transport_na");
            }
            if (StringUtils.isNotEmpty(declaration.getShip_code())) {
                properties.add("ship_code");
            }
            if (properties.size() > 0) {
                declaration.setId(id);
                declaration.setMtime(new Date());
                properties.add("MTIME");
                declarationBiz.updateEntity(declaration, properties);
                msg = MsgConstants.OPERATION_SUCCESS;
                jmsg = Result.newSuccessInstance(msg);
            } else {
                msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), "", "\"}");
                jmsg = Result.newFailInstance(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = String.format("%s%s%s", MsgConstants.OPERATION_FAIL.substring(0, MsgConstants.OPERATION_FAIL.length() - 2), e.getMessage(), "\"}");
            jmsg = Result.newFailInstance(msg);
        }
        try {
            response.setHeader("X-Content-Type-Options", "application/javascript");
            String data = new ObjectMapper().writeValueAsString(jmsg);
            PrintWriter pw = response.getWriter();
            pw.write(String.format("%s(%s)", request.getParameter("callback"), data));
            pw.flush();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
